﻿<%--
 * vendor.aspx
 * 
 * Copyright (C) 2011 Elena Shishkina
 * 
 * This file is part of ServersInventory.
 * 
 * ServersInventory is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ServersInventory is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ServersInventory.  If not, see <http://www.gnu.org/licenses/>.
--%>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Page Language="c#" ContentType="application/json" %>

<script runat="server">
    public SqlConnection DbConnect() {
		var str = new SqlConnectionStringBuilder();
        str.DataSource = WebConfigurationManager.AppSettings["DataSource"];
        str.UserID = WebConfigurationManager.AppSettings["UserID"];
        str.Password = WebConfigurationManager.AppSettings["Password"];
        str.InitialCatalog = WebConfigurationManager.AppSettings["InitialCatalog"];
        var conn = new SqlConnection(str.ToString());
        conn.Open();
		return conn;
	}
    
    public void LoadData()
    {
        try
        {
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from vendors order by name";
                    var items = new List<string>();
                    using (var rd = cmd.ExecuteReader())
                    {

                        while (rd.Read())
                        {
                            var fields = new List<string>();
                            for (var i = 0; i < rd.FieldCount; i++)
                            {
                                fields.Add(String.Format(@"""{0}"":""{1}""", rd.GetName(i), rd.IsDBNull(i) ? "" : rd[i]));
                            }
                            items.Add("{" + string.Join(",", fields.ToArray()) + "}");
                        }

                    }
                    Response.Write("[" + string.Join(",", items.ToArray()) + "]");
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
	
	public void EditVendor() {
		if (string.IsNullOrEmpty(this.Request["id"])) {
			Response.Write("{\"result\": \"ERROR_EMPTY_ID\"}");
			return;
		}
		int id = 0;
		if (!int.TryParse(Request["id"], out id)) {
			Response.Write("{\"result\": \"ERROR_WRONG_ID_FORMAT\"}");
			return;
		}
		if (string.IsNullOrEmpty(Request["name"])) {
			Response.Write("{\"result\": \"ERROR_EMPTY_NAME\"}");
			return;
		}

        using (var conn = DbConnect())
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "update vendors set name = @name, color = @color where id = @id";
                cmd.Parameters.AddWithValue("@name", Request["name"]);
                cmd.Parameters.AddWithValue("@color", Request["color"]);
                cmd.Parameters.AddWithValue("@id", id);
                cmd.ExecuteNonQuery();
            }
            Response.Write("{\"result\": \"RESULT_OK\"}");
        }
	}
	
	public void AddVendor() {
        try
        {
            if (string.IsNullOrEmpty(this.Request["name"]))
            {
                Response.Write("{\"result\": \"ERROR_EMPTY_NAME\"}");
                return;
            }
            using (var conn = DbConnect())
            {
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "insert into vendors (name, color) values (@name, @color); select @@identity;";
                    cmd.Parameters.AddWithValue("@name", Request["name"]);
                    cmd.Parameters.AddWithValue("@color", Request["color"]);
                    Response.Write("{\"result\": \"RESULT_OK\", \"id\": \"" + cmd.ExecuteScalar().ToString() + "\"}");
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
	}
	
	public void RemoveVendor() {
		if (string.IsNullOrEmpty(this.Request["id"])) {
		Response.Write("{\"result\": \"ERROR_EMPTY_ID\"}");
			return;
		}
		int id = 0;
		if (!int.TryParse(Request["id"], out id)) {
			Response.Write("{\"result\": \"ERROR_WRONG_ID_FORMAT\"}");
			return;
		}
        using (var conn = DbConnect())
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "delete from vendors where id = @id";
                cmd.Parameters.AddWithValue("@id", id);
                cmd.ExecuteNonQuery();
            }
            Response.Write("{\"result\": \"RESULT_OK\"}");
        }
	}
	
	public void ProcessRequest()
	{
        Response.AddHeader("Content-type", "application/json");
		if (this.Request["mode"] == "edit") EditVendor();
		else if (this.Request["mode"] == "remove") RemoveVendor();
		else if (this.Request["mode"] == "add") AddVendor();
		else LoadData();
	}
</script>

<% ProcessRequest(); %>

